package com.guoli.print;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class TestPrintF {
	public static void main(String[] args) throws IOException {
		
		String strs[] = getPicString(new String[]{"车型"},"宋体",50);
		
		for(String str : strs){
			System.out.println(str);
		}
		
	}
	public static String[] getPicString(String[] text, String fontName, int fontSize) throws IOException{
		int width = 0;
		int height = 0;
		int ascent = 0;
		String[] picString = new String[text.length];
		Font font = new Font(fontName, Font.BOLD, fontSize);
		for(int i=0;i<text.length;i++){
			Graphics g = new BufferedImage(1, 1, 1).getGraphics();
			FontMetrics fm = g.getFontMetrics(font);
			ascent = fm.getAscent();
			width = (int)Math.round(fm.getStringBounds(text[i], g).getWidth());
			width = width%8!=0?(width/8+1)*8:width;
			height = fm.getHeight();
			height = height%8!=0?(height/8+1)*8:height;
			BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D graphics2d = (Graphics2D) bi.getGraphics();
			graphics2d.setColor(Color.WHITE);
			graphics2d.fillRect(0, 0, width, height);
			graphics2d.setColor(Color.BLACK);
			graphics2d.setFont(font);
			graphics2d.drawString(text[i], 0, ascent);
			File file = new File("C:\\Documents and Settings\\zhuxiaodong\\桌面"+i+".jpg");
			ImageIO.write(bi, "jpg", file);
//			ByteArrayOutputStream bos = new ByteArrayOutputStream();
//			ImageIO.write(bi, "jpg", bos);
//			byte[] picByte = bos.toByteArray();
//			picString[i] = "";
//			for(int j=0;j<picByte.length;j++){
//				String str16 = Integer.toHexString(picByte[j] & 0xff);
//				str16 = str16.length()==1 ? "0"+str16 : str16;
//				picString[i]+=str16;
//			}
			System.out.println("width = "+width+", height = "+height);
			String strx = "";
			String result = "";
			for(int h = 0; h < height; h++){
				for(int w = 0; w < width; w++){
//					if(new Color(bi.getRGB(w, h)).getGreen()==0){
//						strx += "1";
//					}else{
//						strx += "0";
//					}
					strx += new Color(bi.getRGB(w, h)).getGreen()==0?"1":"0";
//					if(w%4==0&&w!=0){
//						result += Integer.toHexString(Integer.parseInt(strx, 2));
//						strx = "";
//					}
//					if(w==(width-1)){
//						strx += "\n";
//					}
				}
			}
			System.out.println("str = \n" + strx);
			System.out.println("result = \n" + result);
			
//			picString[i] = Arrays.toString(picByte);
		}
		return picString;
	}
}
